<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'
  import { reqHomeBanner, reqHomeCategory, reqHomeHot } from '@/api/home'
  import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
  import CustomBar from './components/CustomBar.vue'
  import XtxSwiper from '@/components/XtxSwiper.vue'
  import XtxGuess from '@/components/XtxGuess.vue'
  import CategoryPanel from './components/CategoryPanel.vue'
  import HotPanel from './components/HotPanel.vue'
  import PageSkeleton from './components/PageSkeleton.vue'
  import { useXtxGuessList } from '@/composables'

  // 轮播图列表
  const bannerList = ref<BannerItem[]>([])
  // 获取轮播图
  const getHomeBanner = async () => {
    const res = await reqHomeBanner()
    bannerList.value = res.result
  }

  // 获取前台分类
  const categoryList = ref<CategoryItem[]>([])
  const getHomeCategory = async () => {
    const res = await reqHomeCategory()
    categoryList.value = res.result
  }

  // 获取热门推荐
  const hotList = ref<HotItem[]>([])
  const getHomeHot = async () => {
    const res = await reqHomeHot()
    hotList.value = res.result
  }
  // 骨架屏控制
  const isLoading = ref(false)
  onLoad(async () => {
    // 显示骨架屏
    isLoading.value = true
    // 等待接口
    await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot()])
    // 关闭骨架屏
    isLoading.value = false
  })

  // 使用猜你喜欢组合式函数
  const { guessRef, scrollToLower } = useXtxGuessList()

  // 下拉刷新控制
  const isRefresh = ref(false)
  // 下拉刷新时触发
  const onRefresh = async () => {
    // 开开启下拉刷新
    isRefresh.value = true
    // 重置组件中的数据
    guessRef.value?.resetData()
    // 重新加载数据
    await Promise.all([
      getHomeBanner(),
      getHomeCategory(),
      getHomeHot(),
      guessRef.value?.getHomeGuess()
    ])
    // 关闭下拉刷新
    isRefresh.value = false
  }
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomBar></CustomBar>
  <!-- 骨架屏 -->
  <PageSkeleton v-if="isLoading"></PageSkeleton>
  <scroll-view
    v-else
    scroll-y
    class="scroll"
    refresher-enabled
    :refresher-triggered="isRefresh"
    @scrolltolower="scrollToLower"
    @refresherrefresh="onRefresh"
  >
    <!-- 轮播图 -->
    <XtxSwiper :list="bannerList"></XtxSwiper>
    <!-- 分类 -->
    <CategoryPanel :list="categoryList"></CategoryPanel>
    <!-- 热门推荐 -->
    <HotPanel :list="hotList"></HotPanel>
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef"></XtxGuess>
  </scroll-view>
</template>

<style lang="scss">
  page {
    background-color: #f7f7f7;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .scroll {
    flex: 1;
  }
</style>
